

import guideComponent from '@src/component/guide/Guide';

import { storageSet } from '@src/util/storage';

import GrayUtil from '@src/util/gray';

import { useNewVue } from '@hooks/useNewVue'
const { createVue } = useNewVue();

class Guide {
  constructor(arr = [], nowStep, storageKe, watchStepFn) {
    this.arr = arr;
    this.nowStep = nowStep;
    this.storageKe = storageKe;
    this.vueDom = null;
    this.stepTotalSetting = {};
    if (arr && arr.length && Reflect.has(arr[0], 'stepTotalSetting')) {
      this.stepTotalSetting = arr[0].stepTotalSetting;
    }
    this.stopStep = () => {
      return new Promise((resolve, reject) => {
        if (watchStepFn)
          return watchStepFn({ type: 'stop', nowStep: this.nowStep }).then(
            (res) => {
              if (storageKe) storageSet(storageKe, arr.length);
              resolve();
            }
          );

        if (storageKe) storageSet(storageKe, arr.length);
        resolve();
      });
    };
    this.finishBtnFn = () => {
      return new Promise((resolve, reject) => {
        if (watchStepFn)
          return watchStepFn({ type: 'finish', nowStep: this.nowStep }).then(
            (res) => {
              if (storageKe) storageSet(storageKe, arr.length);
              resolve();
            }
          );

        if (storageKe) storageSet(storageKe, arr.length);
        resolve();
      });
    };
    this.previousStep = () => {
      return new Promise((resolve, reject) => {
        if (this.nowStep == 0) reject();
        if (watchStepFn)
          return watchStepFn({ type: 'pre', nowStep: this.nowStep }).then(
            (res) => {
              this.nowStep--;
              this.create();
              resolve();
            }
          );
        this.nowStep--;
        this.create();
        resolve();
      });
    };
    this.nextStep = () => {
      return new Promise((resolve, reject) => {
        if (this.nowStep == this.arr.length - 1) reject();
        if (watchStepFn)
          return watchStepFn({ type: 'next', nowStep: this.nowStep }).then(
            (res) => {
              this.nowStep++;
              this.create();
              resolve();
            }
          );
        this.nowStep++;
        this.create();
        resolve();
      });
    };
    this.watchContentClick = (e) => {
      if (watchStepFn) {
        return watchStepFn({
          type: 'contentClick',
          nowStep: this.nowStep,
          event: e,
        });
      }
    };
    this.leftBtnFn = () => {
      return new Promise((resolve, reject) => {
        if (watchStepFn) {
          return watchStepFn({ type: 'left', nowStep: this.nowStep }).then(
            (res) => {
              resolve();
            }
          )
        }
        resolve();
      });
    }
  }
  create() {
    return new Promise((resolve, reject) => {
      let obj = this.arr[this.nowStep];
      obj = {...this.stepTotalSetting, ...obj};
      let Test;
      if (obj.diyContentDom) {
        Test = obj.diyContentDom;
      }

      let _this = this;
      const data = {
				..._this.stepTotalSetting,
				totalStep: _this.arr.length,
				nowStep: _this.nowStep * 1 + 1,
				...obj,
				stopStep: _this.stopStep,
				finishBtnFn: _this.finishBtnFn,
				watchContentClick: _this.watchContentClick,
				previousStep: _this.previousStep,
				nextStep: _this.nextStep,
        leftBtnFn: _this.leftBtnFn,
			};
      

      const guideDom = {
        name: 'GuideDom',
        render(h) {
          return (
            <guide-compoment
              class="guide-component"
              totalStep={_this.arr.length}
              canUse={data.canUse}
              inside={data.inside}
              nowStep={_this.nowStep * 1 + 1}
              title={data.title}
              content={data.content}
              needCover={data.needCover}
              finishBtn={data.finishBtn}
              gStyle={data.gStyle}
              id={data.id}
              domId={data.domId}
              domObj={data.domObj}
              diyContent={data.diyContent}
              haveStep={data.haveStep}
              arrowOutsideStyle={data.arrowOutsideStyle}
              stopStep={_this.stopStep}
              finishBtnFn={_this.finishBtnFn}
              watchContentClick={_this.watchContentClick}
              nextStep={_this.nextStep}
              copyDom={data.copyDom}
              direction={data.direction}
              lastFinish={data.lastFinish}
              insideDom={data.insideDom}
              outsideParent={data.outsideParent}
              diyClass={data.diyClass}
              leftBtn={data.leftBtn}
              leftBtnFn={_this.leftBtnFn}
            >
              <template slot="diyContent">
                <Test />
              </template>
            </guide-compoment>
          );
        },
        components: {
          [guideComponent.name]: guideComponent,
          Test,
        },
      };
      let GuideCompoments = createVue(guideDom);
      let el = document.getElementById(`${obj.id}`);
			if(obj.apendToBody){
				el = null;
			}
      if(!el){
        if(el){
          document.body.removeChild(el);
        }
        el =  document.createElement('div');
        el.id = `${data.id}`;
        document.body.appendChild(el);
      }else{
        let par_ = el.parentElement;
        if(el){
          par_.removeChild(el);
        }
        el =  document.createElement('div');
        el.id = `${data.id}`;
        par_.appendChild(el);
      }
      // 使用apendToBody 会在body中自动创建同id dom 需要删除页面中的挂载引导元素同id dom元素
      // if(obj.apendToBody){
      //   let el = document.getElementById(`${obj.id}`);
      //   if(el){
      //     document.body.removeChild(el);
      //   }
      //   el = document.createElement('div');
      //   el.id = `${obj.id}`;
      //   document.body.appendChild(el);
      // }
      
      let vueDom = GuideCompoments;
      vueDom.$mount(el);
      this.vueDom = vueDom;
      resolve(vueDom);
    });
  }
  destroy(id) {
    try {
      // let dom = document.getElementById(`${id}`);
      // dom.remove();
      this.vueDom.$destory()
    } catch (error) {
      console.warn(error, 'error try catch');
    }
  }
}

function domGuide(arr = [], nowStep, storageKe, watchStepFn) {
  if(!arr || arr.length <= 0){
    return {
      create: () => {
        return Promise.resolve(false)
      },
      destroy: () => {
        return Promise.resolve(false)
      },
    };
  }
  let productPreFixedPath = GrayUtil.getProductV2ApiPath();
  let guideType;
  try {
    guideType = arr[0].id.split('-')[0]
  } catch (error) {
    console.warn(error, 'error try catch');
  }
  if ((productPreFixedPath && guideType == 'product') || guideType != 'product') {
    return new Guide(arr, nowStep, storageKe, watchStepFn);
  }
  return {
    create: () => {
      return Promise.resolve(false)
    },
    destroy: () => {
      return Promise.resolve(false)
    },
  };
  
  
}

export default domGuide;
